package com.gaoda.booksystem.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.ForwardAuthenticationSuccessHandler;

/**
 * 安全登录拦截
 */

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService customUserService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService).passwordEncoder(new BCryptPasswordEncoder()); //user Details Service验证
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //解决 SpringSecurityiFrame'X-Frame-Options'to'deny'
        http.headers().frameOptions().disable();
        http.csrf().disable(); //解除拦截
        http.authorizeRequests()
                .antMatchers("/js/**", "/css/**", "/style/**", "/layui/**", "/face_files/**", "/login/**", "/images/**", "/article/**", "/mb/**", "/code/**").permitAll()
                .antMatchers("/mc/**", "/qufen","/register", "/addUser").permitAll()
                .anyRequest().authenticated() //任何请求,登录后可以访问
                .and()
                .formLogin()
                .loginPage("/login")
                //.defaultSuccessUrl("/qufen") //登录成功的默认跳转路径
                // 强制指定登陆成功后跳转的路径
                .successHandler(new ForwardAuthenticationSuccessHandler("/qufen?status=true"))
                .failureUrl("/login?status=false")
                .permitAll() //登录页面用户任意访问
                .and()
                .logout().permitAll(); //注销行为任意访问
        http.logout()
                .logoutUrl("/loginout")//注销操作的URL
                .logoutSuccessUrl("/login")//注销成功后跳转的url
                .invalidateHttpSession(true);//指定是否在注销时让HttpSession无效

    }

}

